package com.weixin.engine.daily.qqhr;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * 私钥生成签名示例代码
 *
 * @author wangchunhui
 * @date 2022/11/1 14:00
 */
public class RsaUtil {
    private final static String SIGN_TYPE_RSA = "RSA";
    private final static String SIGN_ALGORITHMS = "SHA1WithRSA";
    private final static String CHAR_SETTING = "UTF-8";

    /**
     * 使用私钥对字符进行签名
     *
     * @param plain      内容体（需要签名的字符串）
     * @param privateKey 私钥
     * @return String
     * @throws Exception 异常
     */
    public static String sign(String plain, String privateKey) throws Exception {
        if (StringUtils.isBlank(plain) || StringUtils.isBlank(privateKey)) {
            return null;
        }
        PrivateKey privatekey = getPrivateKeyFromPKCS8(SIGN_TYPE_RSA, privateKey);
        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initSign(privatekey);
        signature.update(plain.getBytes(CHAR_SETTING));
        byte[] signed = signature.sign();
        return new String(Base64.encodeBase64(signed));
    }

    /**
     * 获取私钥 PKCS8 格式（需 base64）
     *
     * @param algorithm
     * @param priKey
     * @return PrivateKey
     * @throws Exception
     */
    public static PrivateKey getPrivateKeyFromPKCS8(String algorithm, String priKey) throws Exception {
        if (StringUtils.isBlank(algorithm) || StringUtils.isBlank(priKey)) {
            return null;
        }
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        byte[] encodedKey = Base64.decodeBase64(priKey.getBytes());
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    }
}